//
//  FlashSaleTableViewCell.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/25.
//

import UIKit

class FlashSaleTableViewCell: UITableViewCell {
    
    var titletBtn: UIButton!
    var collectionView: UICollectionView!
    var moreBtn: UIButton!
    var dayBtn: UIButton!//天
    var hourBtn: UIButton!//时
    var minuteBtn: UIButton!//分
    var secondBtn: UIButton!//秒
    var colonLab: UILabel!//冒号
    var colonLab1: UILabel!//冒号
    var colonLab2: UILabel!//冒号
    var timer: Timer!
    var timeCount: NSInteger = 0
    var saleModel: PromotionCotentModel!
    var dataArray: [ProductsDataModel] = []
    var layerView: UIView!
    var bgLayer1: CAGradientLayer!
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?){
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = Theme.F5Color
        self.selectionStyle = .none
        self.clipsToBounds = true
        
        self.initUI()
        self.initCollectionView()
        self.addLayout()
    }
    
    
    func initUI() {
        
        layerView = UIView()
        layerView.frame = CGRect(x: 14, y: 0, width: kScreenWidth - 28, height: 227)
        // fillCode
        bgLayer1 = CAGradientLayer()
        bgLayer1.colors = [UIColor(red: 1, green: 0.91, blue: 0.72, alpha: 1).cgColor, UIColor(red: 1, green: 1, blue: 1, alpha: 1).cgColor]
        bgLayer1.locations = [0, 1]
        bgLayer1.frame = layerView.bounds
        bgLayer1.startPoint = CGPoint(x: 0.5, y: 0)
        bgLayer1.endPoint = CGPoint(x: 1, y: 1)
        layerView.layer.addSublayer(bgLayer1)
        self.contentView.addSubview(layerView)
        
        self.titletBtn = UIButton.init(frame: CGRect.zero)
        self.titletBtn.setTitleColor(Theme.redColor, for: .normal)
        self.titletBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        self.titletBtn.setTitle(MMLocalizedString("flash_sale", comment: "限时抢购"), for: .normal)
        self.titletBtn.setImage(UIImage(named: "icon_flash_arrows"), for: .normal)
        self.titletBtn.semanticContentAttribute = .forceRightToLeft
        self.titletBtn.contentHorizontalAlignment = .left
        self.titletBtn.addTarget(self, action: #selector(moreBtnAntion), for: .touchUpInside)
        self.layerView.addSubview(self.titletBtn)
        
        
        
        self.dayBtn = UIButton(frame: CGRect(x: 10, y: 8, width: 18, height: 18))
        self.dayBtn.titleLabel?.font = UIFont(name:Theme.PingFangSCMedium, size: 12)
        self.dayBtn.setTitleColor(Theme.redColor, for: .normal)
        self.dayBtn.isUserInteractionEnabled = false
        self.dayBtn.contentHorizontalAlignment = .right
        self.layerView.addSubview(self.dayBtn)
        
        self.colonLab = UILabel(frame: CGRect(x: self.dayBtn.right, y: 8, width: 10, height: 18))
        self.colonLab.font = UIFont(name:Theme.PingFangSCMedium, size: 12)
        self.colonLab.textColor = Theme.redColor
        //        self.colonLab.text = ":"
        self.colonLab.textAlignment = .center
        self.layerView.addSubview(self.colonLab)
        
        self.hourBtn = UIButton(frame: CGRect(x: self.colonLab.right, y: 8, width: 18, height: 18))
        self.hourBtn.titleLabel?.font = UIFont(name:Theme.PingFangSCMedium, size: 12)
        self.hourBtn.setTitleColor(Theme.redColor, for: .normal)
        self.hourBtn.isUserInteractionEnabled = false
        self.layerView.addSubview(self.hourBtn)
        
        
        self.colonLab1 = UILabel(frame: CGRect(x: self.hourBtn.right, y: 8, width: 10, height: 18))
        self.colonLab1.font = UIFont(name:Theme.PingFangSCMedium, size: 12)
        self.colonLab1.textColor = Theme.redColor
        self.colonLab1.textAlignment = .center
        self.colonLab1.text = ":"
        self.layerView.addSubview(self.colonLab1)
        
        
        self.minuteBtn = UIButton(frame: CGRect(x: self.colonLab1.right, y: 8, width: 18, height: 18))
        self.minuteBtn.titleLabel?.font = UIFont(name:Theme.PingFangSCMedium, size: 12)
        self.minuteBtn.setTitleColor(Theme.redColor, for: .normal)
        self.minuteBtn.isUserInteractionEnabled = false
        self.layerView.addSubview(self.minuteBtn)
        
        self.colonLab2 = UILabel(frame: CGRect(x: self.minuteBtn.right, y: 8, width: 10, height: 18))
        self.colonLab2.font = UIFont(name:Theme.PingFangSCMedium, size: 12)
        self.colonLab2.textColor = Theme.redColor
        self.colonLab2.textAlignment = .center
        self.colonLab2.text = ":"
        self.layerView.addSubview(self.colonLab2)
        
        self.secondBtn = UIButton(frame: CGRect(x: self.colonLab2.right, y: 8, width: 18, height: 18))
        self.secondBtn.titleLabel?.font = UIFont(name:Theme.PingFangSCMedium, size: 12)
        self.secondBtn.setTitleColor(Theme.redColor, for: .normal)
        self.secondBtn.isUserInteractionEnabled = false
        self.layerView.addSubview(self.secondBtn)
        
        
    }
    
    
    func initCollectionView() {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        self.collectionView = UICollectionView.init(frame: self.bounds, collectionViewLayout: layout)
        self.collectionView.register(FlashSalceCollectionViewCell.self, forCellWithReuseIdentifier: "FlashSalceCollectionViewCell")
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.backgroundColor = .clear
        self.collectionView.contentInset = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 10)
        self.collectionView.showsHorizontalScrollIndicator = false
        layerView.addSubview(self.collectionView)
    }
    
    
    func addLayout() {
        
        self.layerView.snp.makeConstraints { make in
            make.top.equalTo(10)
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.height.greaterThanOrEqualTo(227)
            make.bottom.equalTo(-10)
        }
        bgLayer1.frame = layerView.bounds
        
        self.titletBtn.titleLabel?.frame.size.width = 300
        self.titletBtn.titleLabel?.sizeToFit()
        let tempW: CGFloat = self.titletBtn.titleLabel?.frame.size.width ?? 0
        self.titletBtn.snp.makeConstraints { make in
            make.top.equalTo(10)
            make.left.equalTo(10)
            make.height.equalTo(30)
            make.width.equalTo(tempW + 24)
        }
        
        self.secondBtn.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.left.equalTo(self.colonLab2.snp.right).offset(0)
            make.right.equalTo(-11)
            make.width.equalTo(20)
            make.height.equalTo(30)
        }
        
        self.colonLab2.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.right.equalTo(self.secondBtn.snp.left).offset(0)
            make.width.equalTo(3)
            make.height.equalTo(30)
        }
        
        self.minuteBtn.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.right.equalTo(self.colonLab2.snp.left).offset(0)
            make.width.equalTo(20)
            make.height.equalTo(30)
        }
        
        self.colonLab1.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.right.equalTo(self.minuteBtn.snp.left).offset(0)
            make.width.equalTo(3)
            make.height.equalTo(30)
        }
        
        
        
        self.hourBtn.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.right.equalTo(self.colonLab1.snp.left).offset(0)
            make.width.equalTo(20)
            make.height.equalTo(30)
        }
        
        
        self.colonLab.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.right.equalTo(self.hourBtn.snp.left).offset(0)
            make.width.equalTo(3)
            make.height.equalTo(30)
        }
        
        
        self.dayBtn.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.right.equalTo(self.colonLab.snp.left).offset(0)
            make.height.equalTo(30)
            make.width.greaterThanOrEqualTo(30)
        }
        
        self.collectionView.snp.makeConstraints { make in
            make.top.equalTo(self.titletBtn.snp.bottom).offset(0)
            make.right.equalTo(0)
            make.left.equalTo(0)
            make.bottom.equalTo(0)
        }
    }
    
    
    
    func setSaleModel(saleModel: PromotionCotentModel? = nil){
        guard saleModel != nil else {
            return
        }
        self.saleModel = saleModel
        if self.timer != nil {
            self.timeCount = 0
            self.timer.invalidate()
            self.timer = nil
        }
        self.secondBtn.isHidden = false
        self.colonLab2.isHidden = false
        self.secondBtn.snp.updateConstraints { make in
            make.width.equalTo(20)
        }
        self.colonLab2.snp.updateConstraints { make in
            make.width.equalTo(3)
        }
        
        self.minuteBtn.isHidden = false
        self.colonLab1.isHidden = false
        self.minuteBtn.snp.updateConstraints { make in
            make.width.equalTo(20)
        }
        self.colonLab1.snp.updateConstraints { make in
            make.width.equalTo(3)
        }
        
        
        self.hourBtn.isHidden = false
        self.colonLab.isHidden = false
        self.hourBtn.snp.updateConstraints { make in
            make.width.equalTo(20)
        }
        self.colonLab.snp.updateConstraints { make in
            make.width.equalTo(3)
        }
        
        
        self.timeCount = (saleModel?.activityTime ?? 0)/1000
        let tempStr = XTManageCenter.calculateDateTimeFromNowBySecond(ms: self.timeCount)
        let tempArray = tempStr.components(separatedBy: ":")//没有天的时候隐藏其中秒的格子
        
        self.setTimeContent(timeCount: self.timeCount)
        
        if tempArray.count == 4 {
            self.secondBtn.isHidden = false
            self.colonLab2.isHidden = false
        }else if tempArray.count == 3{
            self.secondBtn.isHidden = true
            self.colonLab2.isHidden = true
            self.secondBtn.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            self.colonLab2.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
        }else if tempArray.count == 2{
            self.secondBtn.isHidden = true
            self.colonLab2.isHidden = true
            self.secondBtn.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            self.colonLab2.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            
            self.minuteBtn.isHidden = true
            self.colonLab1.isHidden = true
            self.minuteBtn.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            self.colonLab1.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
        }else if tempArray.count == 1{
            self.secondBtn.isHidden = true
            self.colonLab2.isHidden = true
            self.secondBtn.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            self.colonLab2.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            
            self.minuteBtn.isHidden = true
            self.colonLab1.isHidden = true
            self.minuteBtn.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            self.colonLab1.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            
            
            self.hourBtn.isHidden = true
            self.colonLab.isHidden = true
            self.hourBtn.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            self.colonLab.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            
        }
        else{
            self.secondBtn.isHidden = true
            self.colonLab2.isHidden = true
        }
        
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self , selector: #selector(timeAction), userInfo: nil, repeats: true)
        RunLoop.current.add(self.timer, forMode: RunLoopMode.commonModes)
        
        
        self.dataArray = saleModel?.products ?? []
        self.collectionView.reloadData()
        self.updateConstraints()
        
    }
    
    //防止第一次服用变一下
    func setTimeContent(timeCount: NSInteger) {
        let tempStr = XTManageCenter.calculateDateTimeFromNowBySecond(ms: self.timeCount)
        let tempArray = tempStr.components(separatedBy: ":")//没有天的时候隐藏其中秒的格子
        if tempArray.count > 0 {
            self.dayBtn.setTitle(String(format: "%@", tempArray[0]), for: .normal)
        }
        if tempArray.count > 1 {
            self.hourBtn.setTitle(String(format: "%@", tempArray[1]), for: .normal)
        }
        if tempArray.count > 2 {
            self.minuteBtn.setTitle(String(format: "%@", tempArray[2]), for: .normal)
        }
        
        if tempArray.count > 3 {
            self.secondBtn.setTitle(String(format: "%@", tempArray[3]), for: .normal)
        }
    }
    
    
    
    @objc func timeAction(){
        if self.timeCount > 0 {
            self.timeCount = self.timeCount - 1
            let tempStr = XTManageCenter.calculateDateTimeFromNowBySecond(ms: self.timeCount)
            let tempArray = tempStr.components(separatedBy: ":")
            if tempArray.count > 0 {
                self.dayBtn.setTitle(String(format: "%@", tempArray[0]), for: .normal)
            }
            if tempArray.count > 1 {
                self.hourBtn.setTitle(String(format: "%@", tempArray[1]), for: .normal)
            }
            if tempArray.count > 2 {
                self.minuteBtn.setTitle(String(format: "%@", tempArray[2]), for: .normal)
            }
            
            if tempArray.count > 3 {
                self.secondBtn.setTitle(String(format: "%@", tempArray[3]), for: .normal)
            }
            
        }else{
            //说明今天的秒杀已过
            self.timeCount = 0
            if self.timer != nil {
                self.timer.invalidate()
                self.timer = nil
            }
            
            self.dayBtn.setTitle("00", for: .normal)
            self.hourBtn.setTitle("00", for: .normal)
            self.minuteBtn.setTitle("00", for: .normal)
            self.secondBtn.setTitle("00", for: .normal)
            //活动结束
            NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "mainRefreash"), object: nil)
        }
    }
    
    
    
    
    //查看更多
    @objc func moreBtnAntion() {
        let vc = FlashSaleViewController()
        vc.saleModel = self.saleModel
        self.viewController().navigationController?.pushViewController(vc, animated: true)
    }
    
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
}

extension FlashSaleTableViewCell: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FlashSalceCollectionViewCell", for: indexPath) as! FlashSalceCollectionViewCell
        if self.dataArray.count > indexPath.row{
            let model = self.dataArray[indexPath.row]
            cell.setProductsModel(productsModel: model)
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        //        let imgH = (kScreenWidth - 36)/2 * (3/4) //图片高度按比例9:16
        return CGSize.init(width: (kScreenWidth - 2*10 - 5)/3, height: 163)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 5
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.dataArray.count > indexPath.row{
            let model = self.dataArray[indexPath.row]
            let vc = ProductDetailsViewController()
            vc.id = model.id ?? 0
            self.viewController().navigationController?.pushViewController(vc, animated: true)
        }
        
    }
    
}


